import pl.dmcs.grails.security.SecurityRole
import pl.dmcs.grails.security.User
import pl.dmcs.grails.security.UserSecurityRole
import pl.dmcs.grails.Employee

class BootStrap {

    def springSecurityService
    
    def init = { servletContext ->
        
        //store security roles
        def dmcsUserRole = SecurityRole.findByAuthority(SecurityRole.USER_ROLE_NAME) ?: new SecurityRole(
            authority: SecurityRole.USER_ROLE_NAME
        ).save(failOnError: true)
        def dmcsAdminRole = SecurityRole.findByAuthority(SecurityRole.ADMIN_ROLE_NAME) ?: new SecurityRole(
            authority: SecurityRole.ADMIN_ROLE_NAME
        ).save(failOnError: true)
        
        //create admin user
        def dmcsAdminUser = Employee.findByUsername('admin') ?: new Employee(
            username: "admin",
            password: "admin",
            title: "admin",
            email: "admin@admin.pl",
            firstName: "admin",
            lastName: "admin",
            room: "admin room",
            enabled: true
        ).save(failOnError: true)

        //assign the admin role
        if (!dmcsAdminUser.authorities.contains(dmcsAdminRole)) {
            UserSecurityRole.create dmcsAdminUser, dmcsAdminRole
        }
    }
    def destroy = {
    }
}
